import axios from 'axios'
import qs from 'qs'
import { IMessage, IMessageBox } from './notice'

axios.defaults.baseURL = process.env.VUE_APP_URL
axios.defaults.timeout = 10000

export function IRequest({ 
        method = 'get', 
        url, 
        data, 
        params}){
    return new Promise((resolve, reject) => {
        axios({
            method: method,
            url: url,
            data: data,
            params: params,
            paramsSerializer: params => {
                return qs.stringify(params, {indices: false})
            }
        }).then(response => {
            const data = response.data
            if(data.success){
                resolve(data)
            }else{
                IMessage({message: data.message ? data.message : response, type: 'error'})
                reject(data)
            }
        }).catch(error => {
            IMessage({message: error, type: 'error'})
            reject(error)
        })
    })
}

export function IMessageBoxRequest({
        message, 
        type,
        url, 
        method = 'get',
        data: data,
        params: params}) {
    return new Promise((resolve, reject) => {
        IMessageBox({
            message,
            type
        }).then(() => {
            return IRequest({
                url,
                method,
                data: data,
                params: params
            })
        }).then(response => {
            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
}
